#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define ROWS 1000
#define COLS 1000

static inline long long now_us(void) {
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC, &ts);
    return (long long)ts.tv_sec * 1000000LL + ts.tv_nsec / 1000;
}

void generate_matrix(double *mat) {
    for (int i = 0; i < ROWS; ++i) {
        for (int j = 0; j < COLS; ++j) {
            mat[i * COLS + j] = (double)rand() / (double)RAND_MAX;
        }
    }
}

// 按行求和
double sum_by_row(const double *mat) {
    double sum = 0.0;
    for (int i = 0; i < ROWS; ++i) {
        const double *row = mat + (size_t)i * COLS;
        for (int j = 0; j < COLS; ++j) {
            sum += row[j];
        }
    }
    return sum;
}

// 按列求和
double sum_by_col(const double *mat) {
    double sum = 0.0;
    for (int j = 0; j < COLS; ++j) {
        for (int i = 0; i < ROWS; ++i) {
            sum += mat[(size_t)i * COLS + j];
        }
    }
    return sum;
}

int main(void) {
    double *matrix = (double *)malloc((size_t)ROWS * COLS * sizeof(double));
    if (!matrix) {
        perror("malloc");
        return 1;
    }

    srand((unsigned)time(NULL));
    generate_matrix(matrix);

    // 按行计时
    long long t0 = now_us();
    double sum_row = sum_by_row(matrix);
    long long t1 = now_us();

    // 按列计时
    long long t2 = now_us();
    double sum_col = sum_by_col(matrix);
    long long t3 = now_us();

    long long dur_row = t1 - t0;
    long long dur_col = t3 - t2;

    printf("按行读取矩阵的时间: %lld 微秒\n", dur_row);
    printf("按列读取矩阵的时间: %lld 微秒\n", dur_col);
    printf("时间差: %lld 微秒\n", (dur_col - dur_row));
    printf("校验: sum_row=%.6f, sum_col=%.6f\n", sum_row, sum_col);

    free(matrix);
    return 0;
}
